<template>
  <div class="api-manager page-container">
    <div class="page-header">
      <h2 class="page-title">API管理</h2>
      <a-button type="primary" @click="showAddForm = true">
        <template #icon><PlusOutlined /></template>
        添加新API
      </a-button>
    </div>
    
    <!-- API列表 -->
    <div class="api-list">
      <a-table :dataSource="apiList" :columns="columns" :pagination="false" bordered>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'method'">
            <a-tag :color="getMethodColor(record.method)">{{ record.method }}</a-tag>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 'active' ? 'success' : 'default'">
              {{ record.status === 'active' ? '已启用' : '未启用' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="text" @click="editApi(record)">
                <template #icon><EditOutlined /></template>
              </a-button>
              <a-button type="text" @click="testApi(record)">
                <template #icon><PlayCircleOutlined /></template>
              </a-button>
              <a-button type="text" danger @click="deleteApi(record)">
                <template #icon><DeleteOutlined /></template>
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- API测试对话框 -->
    <a-modal
      v-model:open="testDialogVisible"
      title="API测试"
      :width="800"
      @cancel="testDialogVisible = false"
    >
      <div class="test-dialog-content">
        <!-- 请求配置部分 -->
        <div class="request-config">
          <h4>请求配置</h4>
          <a-form :model="testForm" layout="vertical">
            <a-form-item label="请求头">
              <div v-for="(header, index) in testForm.headers" :key="index" class="header-item">
                <a-input v-model:value="header.key" placeholder="Header名称" style="width: 200px" />
                <a-input v-model:value="header.value" placeholder="Header值" style="width: 200px; margin: 0 10px" />
                <a-button type="text" danger @click="removeHeader(index)">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </div>
              <a-button type="primary" @click="addHeader">
                <template #icon><PlusOutlined /></template>
                添加请求头
              </a-button>
            </a-form-item>
            
            <a-form-item label="请求参数" v-if="currentApi.sqlQuery">
              <a-alert
                message="参数格式说明"
                description="请按JSON格式输入SQL查询参数，参数名需要与SQL中的 :param_name 占位符对应"
                type="info"
                show-icon
              />
              <a-textarea
                v-model:value="testForm.body"
                :rows="5"
                placeholder='请输入JSON格式的参数，例如：{"id": 1, "name": "test"}'
                class="mt-3"
              />
            </a-form-item>
            <a-form-item label="请求体" v-else-if="currentApi.method !== 'GET'">
              <a-textarea
                v-model:value="testForm.body"
                :rows="5"
                placeholder="请输入JSON格式的请求体"
              />
            </a-form-item>
          </a-form>
        </div>
        
        <!-- 响应结果部分 -->
        <div class="response-result" v-if="testResponse">
          <h4>响应结果</h4>
          <div class="response-info">
            <p>状态码: 
              <a-tag :color="testResponse.status >= 200 && testResponse.status < 300 ? 'success' : 'error'">
                {{ testResponse.status }}
              </a-tag>
            </p>
            <div class="response-headers">
              <p>响应头:</p>
              <a-descriptions bordered :column="1">
                <a-descriptions-item v-for="(value, key) in testResponse.headers" :key="key" :label="key">
                  {{ value }}
                </a-descriptions-item>
              </a-descriptions>
            </div>
            <div class="response-body">
              <p>响应体:</p>
              <pre>{{ JSON.stringify(testResponse.body, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <a-space>
          <a-button @click="testDialogVisible = false">关闭</a-button>
          <a-button type="primary" @click="currentApi.sqlQuery ? testSqlQuery() : executeTest()">
            执行测试
          </a-button>
        </a-space>
      </template>
    </a-modal>

    <!-- 添加/编辑API表单 -->
    <a-modal
      v-model:open="showAddForm"
      :title="isEditing ? '编辑API' : '添加新API'"
      :width="800"
      @ok="submitForm"
      @cancel="showAddForm = false"
    >
      <a-form
        ref="apiFormRef"
        :model="apiForm"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="API名称" name="name">
          <a-input v-model:value="apiForm.name" placeholder="请输入API名称" />
        </a-form-item>
        <a-form-item label="请求方法" name="method">
          <a-select v-model:value="apiForm.method" placeholder="请选择请求方法">
            <a-select-option value="GET">GET</a-select-option>
            <a-select-option value="POST">POST</a-select-option>
            <a-select-option value="PUT">PUT</a-select-option>
            <a-select-option value="DELETE">DELETE</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="路径" name="path">
          <a-input v-model:value="apiForm.path" placeholder="请输入API路径" />
        </a-form-item>
        <a-form-item label="数据库连接" name="dbConnection">
          <a-select v-model:value="apiForm.dbConnection" placeholder="请选择数据库连接">
            <a-select-option
              v-for="conn in dbConnections"
              :key="conn.id"
              :value="conn.id"
            >
              {{ conn.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="SQL语句" name="sqlQuery">
          <a-textarea
            v-model:value="apiForm.sqlQuery"
            :rows="5"
            placeholder="请输入SQL查询语句"
            class="sql-editor"
          />
          <a-alert
            message="SQL编写提示"
            description="支持SELECT语句查询，支持参数占位符 :param_name 格式"
            type="info"
            show-icon
            class="mt-3"
          />
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="apiForm.description"
            :rows="3"
            placeholder="请输入API描述"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import axios from 'axios'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  PlayCircleOutlined
} from '@ant-design/icons-vue'

const apiList = ref([])
const apiFormRef = ref(null)
const isEditing = ref(false)
const showAddForm = ref(false)
const dbConnections = ref([])

// API表单数据
const apiForm = ref({
  name: '',
  method: 'GET',
  path: '',
  dbConnection: '',
  sqlQuery: '',
  description: '',
  status: 'inactive'
})

// API测试相关的响应式数据
const testDialogVisible = ref(false)
const currentApi = ref({
  sqlQuery: '',
  method: 'GET',
  dbConnection: '',
  id: ''
})
const testForm = ref({
  headers: [],
  body: ''
})
const testResponse = ref(null)

// 表格列定义
const columns = [
  {
    title: 'API名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '请求方法',
    dataIndex: 'method',
    key: 'method',
    width: 100
  },
  {
    title: '路径',
    dataIndex: 'path',
    key: 'path',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入API名称', trigger: 'blur' }],
  method: [{ required: true, message: '请选择请求方法', trigger: 'change' }],
  path: [{ required: true, message: '请输入API路径', trigger: 'blur' }],
  dbConnection: [{ required: true, message: '请选择数据库连接', trigger: 'change' }],
  sqlQuery: [{ required: true, message: '请输入SQL查询语句', trigger: 'blur' }]
}

// 获取请求方法对应的颜色
const getMethodColor = (method) => {
  const colors = {
    GET: 'success',
    POST: 'processing',
    PUT: 'warning',
    DELETE: 'error'
  }
  return colors[method] || 'default'
}

// 获取API列表
const fetchAPIs = async () => {
  loading.value = true
  try {
    const res = await axios.get('/api/apis')
    apis.value = res.data
  } catch (error) {
    console.error('获取API列表失败:', error)
    apis.value = []
  } finally {
    loading.value = false
  }
}

// 创建API
const createAPI = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    const res = await axios.post('/api/apis', form.value)
    if (res.code === 200) {
      message.success('创建API成功')
      showForm.value = false
      fetchAPIs()
    }
  } catch (error) {
    console.error('创建API失败:', error)
  }
}

// 更新API
const updateAPI = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    const res = await axios.put(`/api/apis/${form.value.id}`, form.value)
    if (res.code === 200) {
      message.success('更新API成功')
      showForm.value = false
      fetchAPIs()
    }
  } catch (error) {
    console.error('更新API失败:', error)
  }
}

// 删除API
const deleteAPI = async (id) => {
  try {
    const res = await Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个API吗？',
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        const res = await axios.delete(`/api/apis/${id}`)
        if (res.code === 200) {
          message.success('删除API成功')
          fetchAPIs()
        }
      }
    })
  } catch (error) {
    console.error('删除API失败:', error)
  }
}

// 测试API
const testAPI = async (api) => {
  try {
    const res = await axios.post(`/api/apis/${api.id}/test`, {
      params: testParams.value
    })
    if (res.code === 200) {
      testResult.value = res.data
      showTestResult.value = true
    }
  } catch (error) {
    console.error('测试API失败:', error)
    testResult.value = {
      success: false,
      message: error.message,
      data: null
    }
    showTestResult.value = true
  }
}

// 获取API详情
const getAPIDetails = async (id) => {
  try {
    const res = await axios.get(`/api/apis/${id}`)
    if (res.code === 200) {
      currentAPI.value = res.data
      showDetails.value = true
    }
  } catch (error) {
    console.error('获取API详情失败:', error)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await apiFormRef.value.validate()
    const url = isEditing.value ? `/api/apis/${apiForm.value.id}` : '/api/apis'
    const method = isEditing.value ? 'put' : 'post'
    
    const response = await axios[method](url, apiForm.value)
    
    message.success(isEditing.value ? 'API更新成功' : 'API创建成功')
    await fetchAPIs()
    showAddForm.value = false
    resetForm()
  } catch (error) {
    console.error('提交表单失败:', error)
    if (error.response) {
      message.error(`操作失败: ${error.response.data?.message || '服务器错误'}`)
    } else {
      message.error(`操作失败: ${error.message}`)
    }
  }
}

// 编辑API
const editApi = (api) => {
  isEditing.value = true
  apiForm.value = { ...api }
  showAddForm.value = true
}

// 删除API
const deleteApi = async (api) => {
  try {
    await Modal.confirm({
      title: '警告',
      content: '确定要删除这个API吗？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消'
    })
    
    await deleteAPI(api.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除API失败:', error)
      if (error.response) {
        message.error(`删除失败: ${error.response.data?.message || '服务器错误'}`)
      } else {
        message.error(`删除失败: ${error.message}`)
      }
    }
  }
}

// 测试API
const testApi = (api) => {
  currentApi.value = api
  testForm.value = {
    headers: [],
    body: ''
  }
  testResponse.value = null
  testDialogVisible.value = true
}

// 添加请求头
const addHeader = () => {
  testForm.value.headers.push({ key: '', value: '' })
}

// 删除请求头
const removeHeader = (index) => {
  testForm.value.headers.splice(index, 1)
}

// 执行API测试
const executeTest = async () => {
  try {
    // 构建请求头
    const headers = {
      'Content-Type': 'application/json'
    }
    testForm.value.headers.forEach(header => {
      if (header.key && header.value) {
        headers[header.key] = header.value
      }
    })

    // 发送测试请求
    const response = await axios({
      method: currentApi.value.method.toLowerCase(),
      url: `/api/apis/${currentApi.value.id}/test`,
      headers,
      data: currentApi.value.method !== 'GET' ? testForm.value.body : undefined
    })

    // 设置测试响应结果
    testResponse.value = {
      status: response.status,
      headers: response.headers,
      body: response.data
    }

    message.success('API测试执行成功')
  } catch (error) {
    console.error('API测试执行失败:', error)
    if (error.response) {
      testResponse.value = {
        status: error.response.status,
        headers: error.response.headers,
        body: error.response.data
      }
      message.warning('API测试返回非成功状态码')
    } else {
      message.error(`API测试执行失败: ${error.message}`)
    }
  }
}

// 重置表单
const resetForm = () => {
  if (apiFormRef.value) {
    apiFormRef.value.resetFields()
  }
  isEditing.value = false
  apiForm.value = {
    name: '',
    method: 'GET',
    path: '',
    description: '',
    status: 'inactive'
  }
}

// 获取数据库连接列表
const fetchDbConnections = async () => {
  try {
    const response = await axios.get('/api/db-connections')
    dbConnections.value = response.data
  } catch (error) {
    console.error('获取数据库连接列表失败:', error)
    if (error.response) {
      message.error(`获取数据库连接列表失败: ${error.response.data?.message || '服务器错误'}`)
    } else if (error.request) {
      message.error('获取数据库连接列表失败: 无法连接到服务器')
    } else {
      message.error(`获取数据库连接列表失败: ${error.message}`)
    }
    dbConnections.value = []
  }
}

// 测试SQL查询
const testSqlQuery = async () => {
  try {
    const response = await axios.post(`/api/db-connections/${currentApi.value.dbConnection}/test`, {
      sql: currentApi.value.sqlQuery,
      params: JSON.parse(testForm.value.body || '{}')
    })

    testResponse.value = {
      status: response.status,
      headers: response.headers,
      body: response.data
    }

    message.success('SQL查询测试执行成功')
  } catch (error) {
    console.error('SQL查询测试执行失败:', error)
    if (error.response) {
      testResponse.value = {
        status: error.response.status,
        headers: error.response.headers,
        body: error.response.data
      }
      message.warning('SQL查询测试返回非成功状态码')
    } else {
      message.error(`SQL查询测试执行失败: ${error.message}`)
    }
  }
}

onMounted(() => {
  fetchAPIs()
  fetchDbConnections()
})
</script>

<style scoped>
.api-manager {
  padding: 24px;
  max-width: 1440px;
  margin: 0 auto;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: rgba(0, 0, 0, 0.85);
}

.api-list {
  margin-bottom: 32px;
}

.test-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

.header-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.response-info {
  margin-top: 16px;
}

.response-headers,
.response-body {
  margin-top: 16px;
}

.response-body pre {
  background-color: #fafafa;
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: monospace;
}

.sql-editor {
  margin-bottom: 8px;
}

.mt-3 {
  margin-top: 16px;
}

.error-details {
  color: #ff4d4f;
}

@media (max-width: 768px) {
  .api-manager {
    padding: 16px;
  }

  .page-header {
    padding: 12px 16px;
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .page-title {
    font-size: 20px;
    text-align: center;
  }
}
</style>